package com.gitee.fantaros.web.fan.netcut.util;

import io.github.fantaros.cipher.WhisperAlgorithm;
import io.github.fantaros.cipher.data.WhisperKey;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Slf4j
public class WhisperUtil {

    private static final String WHISPER_KEY_PASSWD = "fan&netcut%paster!pass|word*";
    private static final int BLOCK_SIZE = 3;

    public static String encodeString(String baseStr) {
        try {
            log.info("encode before:{}", baseStr);
            byte[] originalData = baseStr.getBytes(StandardCharsets.UTF_8);
            WhisperKey key = WhisperKey.whisperKeyWithPassword(WHISPER_KEY_PASSWD);
            byte[] output = WhisperAlgorithm.encrypt(WhisperAlgorithm.addHeader(originalData), key, BLOCK_SIZE);
            String encoded = Base64.getEncoder().encodeToString(output);
            log.info("encode after:{}", encoded);
            return encoded;
        } catch (Exception e) {
            return baseStr;
        }
    }

    public static String decodeString(String base64Str) {
        try {
            log.info("decode before:{}", base64Str);
            byte[] encodedBytes = Base64.getDecoder().decode(base64Str);
            WhisperKey key = WhisperKey.whisperKeyWithPassword(WHISPER_KEY_PASSWD);
            byte[] deCryptoBytes = WhisperAlgorithm.decrypt(encodedBytes, key, BLOCK_SIZE);
            byte[] originalBytes = WhisperAlgorithm.decodeContent(deCryptoBytes);
            String originalString = new String(originalBytes, StandardCharsets.UTF_8);
            log.info("decode after:{}", originalString);
            return originalString;
        } catch (Exception e) {
            return base64Str;
        }
    }

}
